<template>
  <div class="animate__animated animate__fadeIn">
    <el-card>
      <!--搜索部分-->
      <div class="search-container"  >
        <div class="search-box" v-show="searchShow">
          <el-input prefix-icon="el-icon-search" v-model="searchCondition.roleName" placeholder="请输角色名称..."
                    size="small" clearable @clear="initrole" style="margin-right: 10px;width: 25%;"/>
          <el-input prefix-icon="el-icon-search" v-model="searchCondition.roleKey" placeholder="请输入角色主键..."
                    size="small" clearable @clear="initrole" style="margin-right: 10px;width: 25%;"/>
          <el-select size="small" v-model="searchCondition.isDisable" placeholder="角色状态"
                     clearable @clear="initrole" style="margin-left: 10px;width: 15%;">
            <el-option
                v-for="item in isDisable"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
           <el-button icon="el-icon-search" type="primary" size="small" @click="initrole"  style="margin-left: 10px">搜索</el-button>
    
          <el-button :disabled="deleteList.length === 0" slot="reference" icon="el-icon-delete" type="danger" size="small" @click="deleteLogsInfo">批量删除</el-button>
       
        </div>
          <!--添加部分-->
        <div class="save-container">
          <!--添加-->
          <div class="save-box">
            <el-button type="success" size="small" plain icon="el-icon-plus" @click="saveMenuVisible = true">添加角色
            </el-button>
          </div>
          <!--关闭-->
          <div class="close-box">
            <el-tooltip content="关闭查询" placement="bottom">
              <el-button type="primary" size="small" plain circle icon="el-icon-search"
                         @click="searchShow = !searchShow"/>
            </el-tooltip>
            <el-tooltip content="刷新数据" placement="bottom">
              <el-button type="success" size="small" plain circle icon="el-icon-refresh" @click="initrole"/>
            </el-tooltip>
          <el-tooltip content="显隐列" placement="bottom">
              <el-button type="warning" size="small" plain circle icon="el-icon-menu" @click="transferVisible = true"/>
            </el-tooltip>
          </div>
        </div>
      </div>

      <!--表格部分-->
      <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="roleList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="selectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('角色名称')"
            align="center"
            prop="roleName"
            label="角色名称"
            min-width="50">
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('角色主键')"
            align="center"
            prop="roleKey"
            label="角色主键"
            min-width="100">
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('角色标识')"
            align="center"
            prop="roleNum"
            label="角色标识"
            width="100">
        </el-table-column>
         <el-table-column
             v-if="!transferValue.includes('状态')"
            align="center"
            label="状态"
            width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isDisable" type="danger">禁用</el-tag>
            <el-tag v-else >正常</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            v-if="!transferValue.includes('创建者')"
            align="center"
            prop="createBy"
            label="创建者"
            width="150">
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('创建时间')"
            align="center"
            prop="gmtCreate"
            label="创建时间"
            width="240">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ scope.row.gmtCreate }}
          </template>
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('修改者')"
            align="center"
            prop="updateBy"
            label="修改者"
            width="150">
        </el-table-column>
  
        <el-table-column
            v-if="!transferValue.includes('修改时间')"
            align="center"
            prop="gmtUpdate"
            label="修改时间"
            min-width="140">
                <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ scope.row.gmtUpdate }}
          </template>
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('备注')"
            align="center"
            prop="remark"
            label="备注"
            width="90">
        </el-table-column>
        <el-table-column
            align="center"
            width="260"
            label="操作">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="toUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteLogInfo(scope.row.roleId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页部分-->
      <el-pagination
          class="page"
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="searchCondition.current"
          :page-sizes="[8, 16, 32]"
          :page-size="8"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!--显隐列 弹出层-->
    <el-dialog
        title="显隐列设置"
        :visible.sync="transferVisible"
        width="45%"
        append-to-body
        center>
      <el-transfer
          v-model="transferValue"
          :data="transferData"
          :titles="transferTitles">
      </el-transfer>
    </el-dialog>
    
<!--分配角色权限的对话框-->
<el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" :append-to-body="true" @close="showSetRightDialogClosed">
      <!--内容主体区域 树形控件-->
      <el-tree :data="rightsList" :check-strictly="isCheck" :props="treeProps" show-checkbox default-expand-all  node-key="menuId" ref="treeRef"></el-tree>

      <!--底部按钮区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false" @close="showSetRightDialogClosed">取 消</el-button>
        <el-button type="primary" @click="allotRigths">确 定</el-button>
      </span>
</el-dialog>

 <!--新增 弹出层-->
    <el-drawer
       :title="roleVo.roleId === -1?'新增角色信息':'修改角色信息'"
        :visible.sync="saveMenuVisible"
        append-to-body
        direction="rtl"
        size="28%"
        :before-close="leave">
      <div class="save-container">
        <el-form ref="roleVoCheck" :rules="rule" :model="roleVo" label-width="90px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleVo.roleName" border label="menu" placeholder="请输入角色名称..."/>
          </el-form-item>
          <el-form-item label="角色主键" prop="roleKey">
            <el-input v-model="roleVo.roleKey" border label="menu" placeholder="请输入角色主键..."/>
          </el-form-item>
          <el-form-item label="角色排序">
            <el-input-number size="small" v-model="roleVo.roleNum"/>
          </el-form-item>
          <el-form-item label="角色状态">
          <el-select size="small" v-model="roleVo.isDisable" 
                       style="width: 45%;">
            <el-option
                v-for="item in isDisable"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>

          </el-form-item>
          

          <el-form-item label="备注信息" align="center">
            <el-input type="textarea" :rows="3" placeholder="请输入备注信息..." v-model="roleVo.remark"/>
          </el-form-item>
          <el-form-item align="center">
            <el-button icon="el-icon-sunny" size="small" type="success" plain @click="saveMenuContent('roleVoCheck')">
              确定
            </el-button>
            <el-popconfirm
                v-if="roleVo.roleId === -1"
                style="margin-left: 10px"
                title="确定要重置角色信息吗？"
                @confirm="clearForm">
              <el-button icon="el-icon-refresh" size="small" type="warning" plain slot="reference">重置</el-button>
            </el-popconfirm>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>


  </div>
</template>

<script>
import {formatTimeToYMD} from "../../../utils/timeUtil";
import {listRole} from "../../../api/role/role";
import {transferTitles, transferData} from "@/assets/const/role";
import {saveRole,
        deleteRole,
        deleteRoleList,
        updateRoleMenu,
        updateRole
} from "../../../api/role/role";
import {listMenu,
        listByRoleId
        } from "../../../api/menu/permApi";
import {resultCheck} from "../../../utils/result";
import {messageInfo} from "@/utils/MessageInfo";

export default {
  data() {
    return {
      logList: [],
      roleList: [],
      loading: false,
      isCheck: false,
      deleteList: [],
      total: 0,
      roleID: '',
      setRightDialogVisible: false, // 控制分配角色权限对话框是否显示
      rightsList: [], // 角色所有权限数据
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'menuName',
        children: 'children'
      },
  
      time: [],
      switchValue: true, // 设置默认值为开启状态
      searchShow: true,   //查询功能是否开启
      searchCondition: {
        current: 1,
        size: 8,
        roleName: "",
        roleKey: "",
        isDisable: null
      },
      isDisable: [
        {value: 0, label: "正常"},
        {value: 1, label: "禁用"}
      ],
      //=======================  穿梭表单  ===========================
      transferTitles: transferTitles(),  //穿梭表单title
      transferValue: ['创建者', '创建时间', '修改者', '修改时间'],               //穿梭表单选中数据
      transferData: transferData(),      //穿梭表单数据
      transferVisible: false,            //显隐列是否开启
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //=======================  角色  ===========================
      saveMenuVisible: false,   //新增角色
      menuType: "menu",
      rule: {
        roleName: [{required: true, message: '角色名称不能为空！', trigger: 'blur'}],
        roleKey: [{required: true, message: '角色路由不能为空！', trigger: 'blur'}]
      },
      roleVo: {
        roleId: -1,
        roleName: '',
        roleKey: '',
        roleNum: 99,
        isDisable: 0,
        remark: ''
      },
        init: {
        roleId: -1,
        roleName: '',
        roleKey: '',
        roleNum: 99,
        isDisable: 0,
        remark: ''
      }
    }
  },
  mounted() {
        this.initrole();
  },
  methods: {
    //=======================  查询操作  ===========================
  
    initrole() {
      this.loading = true;
      listRole(this.searchCondition).then(res => {
        var data = resultCheck(res, false);
        this.roleList = data.data;
        this.total = data.total;
        this.loading = false;
      });
    },
    sizeChange(val) {
      this.searchCondition.size = val;
      this.initrole();
    },
    currentChange(val) {
      this.searchCondition.current = val;
      this.initrole();
    },
    // 时间变换
    change() {
      this.searchCondition.beginTime = formatTimeToYMD(this.time[0]);
      this.searchCondition.endTime = formatTimeToYMD(this.time[1]);
    },
    // 展示分配权限的对话框
    showSetRightDialog(role) {
       this.roleID = role.roleId;
      // 获取所有权限列表 树形
       listMenu().then(res => {
         resultCheck(res, false);
         this.rightsList = res.data
            // 获取所有权限列表 树形
       listByRoleId(role.roleId).then(res => {
         resultCheck(res, false);
  
       this.isCheck= true  //重点：给数节点赋值之前 先设置为true
       this.$nextTick(() => {
        //因为我是根据数据id来判断选中所以使用setCheckedKeys，具体可以查看element官网api
        this.$refs.treeRef.setCheckedKeys( res.data) //给树节点赋值
        this.isCheck= false //重点： 赋值完成后 设置为false
  })


          this.setRightDialogVisible = true
       });
       });
      
        
    },
// 点击按钮 给角色分配权限
async allotRigths(id) {
     const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
     const idStr = keys.join(',')
     const data = {
        roleId: this.roleID,
        idList: idStr
      };
     updateRoleMenu(data).then(res => {
         resultCheck(res, true);
  
             this.rightsList = [];
             this.setRightDialogVisible = false;
     });
     
},
// 监听 分配权限对话框的关闭事件
showSetRightDialogClosed() {

    this.rightsList = [];
},


  
      // 批量删除
    selectionChange(val) {
        this.deleteList = val;
    },
   //=======================  删除操作  ===========================
    //  删除角色信息
    deleteLogInfo(id) {
        this.$confirm(`确认要删除此角色信息吗？`, {
        type: 'warning',
        dangerouslyUseHTMLString: true
         }).then(_ => {
        deleteRole(id).then(res => {
         resultCheck(res, true);
         this.initrole();
       });
      
      });

    },
    //  批量删除角色信息
    deleteLogsInfo() {

    this.$confirm(`确认要删除选中的角色信息吗？`, {
        type: 'warning',
        dangerouslyUseHTMLString: true
         }).then(_ => {
        const idList = [];
        this.deleteList.forEach(item => {
         idList.push(item.roleId);
         })
       deleteRoleList(idList).then(res => {
         resultCheck(res, true);
         this.initrole();
       });
       });

    },
    //=======================  新增/修改角色部分  ===========================
    leave() {
      this.$confirm('数据不会临时保存，切勿离开此界面！')
          .then(_ => {
            this.roleVo = this.init;
            this.saveMenuVisible = false;
          });
    },
    //  清空表单信息
    clearForm() {
         this.roleVo = this.init;
    },
    //  跳转至修改界面
    toUpdate(data) {
      this.roleVo = data;
      this.saveMenuVisible = true;
    },
    //  跳转至新增界面
    toSave(roleId) {
      this.roleVo.roleId = -1;
      this.menuType = 'content';
      this.saveMenuVisible = true;
    },
    //  添加角色信息
    saveMenuContent(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.roleVo.roleId == -1) {
              saveRole(this.roleVo).then(res => {
                resultCheck(res, true);
                   this.roleVo = this.init;
                       this.initrole();
              });
          } else {
            updateRole(this.roleVo).then(res => {
              resultCheck(res, true);
                 this.roleVo = this.init;
                     this.initrole();
            });
          }
      
          this.saveMenuVisible = false;
        }
      });
    },
  }
}
</script>

<style scoped>
.search-container {
  display: flex;
  flex-direction: column;
}

.search-box {
  display: flex;
  justify-content: left;
}

.time-box {
  display: flex;
  justify-content: left;
  margin-top: 10px;
}
.save-container {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.page{
  display: flex;
  justify-content: right;
  margin-top: 10px;
}
</style>